package com.test.sshsitemesh.framework;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Expression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class BaseHibernateDAO<E, PK extends Serializable> implements EntityDAO<E, PK> {

	public Class getEntityClass() {
		Class c = getClass();
		Type t = c.getGenericSuperclass();
		if (t instanceof ParameterizedType) {
			Type[] p = ((ParameterizedType) t).getActualTypeArguments();
			return (Class<E>) p[0];
		}

		return null;
	}
	
	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;
	
	public Session getSession() {
		// 事务必须是开启的，否则获取不到

		Session session = sessionFactory.getCurrentSession();

		return session;
	}
	
	@Override
	public List<E> findAllBy(final String[] propertyNames, final Object[] values){
		Criteria criteria = getSession().createCriteria(getEntityClass());
		if(propertyNames == null || values == null || propertyNames.length != values.length){
			return null;
		}
		for(int i = 0;i<propertyNames.length;i++)
		{
			criteria.add(Expression.eqOrIsNull(propertyNames[i], values[i]));
		}
		return criteria.list();
	}
	
	@Override
	public List<E> find(String hql, Map<String, Object> values) {

		if(values == null){
			values = new HashMap<String,Object>();
		}
		Query query = getSession().createQuery(hql);
		query.setProperties(values);
		return query.list();
	}
	
	@Override
	public List<E> findByHql(String hql,Object[] values){
		Query query = getSession().createQuery(hql);
		if(values != null){
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		return query.list();
	}
	
}
